package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.rides.RedisCacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.mysql.jdbc.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private IWemediaClient iWemediaClient;
    @Autowired
    private RedisCacheService redisCacheService;

    /**
     * 计算热点文章存入redis
     */
    @Override
    public void computeHotArticle() {
        //1.查询前5天的文章数据
        Date date = DateTime.now().minusDays(5).toDate();
        List<ApArticle> apArticles = apArticleMapper.hot5ArticleList(date);
        //2.计算文章的分值
        List<HotArticleVo> hotArticleVos = computeArticle(apArticles);

        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVos);
    }


    /**
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        //先查询所有频道
        ResponseResult responseResult = iWemediaClient.getChannels();

        if(responseResult.getCode().equals(200)){
            String channelJson = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(channelJson, WmChannel.class);

            if (wmChannels != null && wmChannels.size() > 0) {
                //在每个频道中过滤属于这个频道的文章
                for (WmChannel wmChannel : wmChannels) {
                    hotArticleVos.stream()
                            .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());

                //给文章排序存入redis中
                    sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId());
                }
            }
        }
        //设置推荐数据
        //给文章进行排序，取30条分值较高的文章存入redis  key：频道id   value：30条分值较高的文章
        sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 文章排序并存入redis
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {

        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size() > 30) {
            hotArticleVos = hotArticleVos.subList(0, 30);
        }
        redisCacheService.set(key,JSON.toJSONString(hotArticleVos));
    }


    /**
     * 计算文章分值并转成热点文章对象
     *
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> computeArticle(List<ApArticle> apArticles) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        //循环拷贝
        if (apArticles != null && apArticles.size() > 0) {
            for (ApArticle apArticle : apArticles) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hot);
                Integer score = computeScore(apArticle);
                hot.setScore(score);
                hotArticleVoList.add(hot);
            }
        }
        return hotArticleVoList;
    }

    /**
     * 计算每一篇文章的具体分值
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer scere = 0;
        if (apArticle.getLikes() != null) {
            scere += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            scere += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            scere += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return scere;
    }
}
